import time

from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from util.DataQuery.FormDataDecorator import FormDataDecorator

# # # # # # # # ######## # # #   填写   知识产权汇总表                                        3################################              ###############################
from util.g import g


class WriteIPForm():
    form_btn_loc = (By.LINK_TEXT, '知识产权汇总表')
    title_loc = (By.CSS_SELECTOR, 'h2.text-center')
    content_iframe_loc = (By.CSS_SELECTOR, "#innocomFrame")
    #    添加按钮
    # add_btn_loc = (By.CSS_SELECTOR, '.form-group.pull-right .blue')
    add_btn_loc = (By.XPATH, "//div[@class='form-group pull-right']/button[contains(string(), '添加')]")
    #    删除按钮
    # delete_btn_loc = (By.CSS_SELECTOR, '.table-search div:nth-of-type(2) button')
    delete_btn_loc = (By.XPATH, "//div[@class='form-group pull-right']/button[contains(string(), '删除')]")
    #    查找按钮
    # query_btn_loc = (By.CSS_SELECTOR, '.table-search div:nth-of-type(3) button')
    query_btn_loc = (By.XPATH, "//div[@class='form-group pull-right']/button[contains(string(), '查找')]")

    ipr_num_loc = (By.CSS_SELECTOR, 'input#propertyNo')
    ipr_type_loc = (By.CSS_SELECTOR, 'select#propertyCategory')
    # # 专利号         3#     #         # 填写专利号时，如果在国网填写需要将 专利号 auth_num 开头的 CN 换成 ZL
    patent_num_loc = (By.CSS_SELECTOR, 'input#propertyAccredit')

    ipr_name_loc = (By.CSS_SELECTOR, 'input#propertyName')
    ipr_getway_loc = (By.CSS_SELECTOR, 'select#propertyWay')
    auto_date_loc = (By.CSS_SELECTOR, 'input#txtDate')
    auto_date_js_str = "document.getElementById('txtDate').removeAttribute('readonly')"

    # # 上传附件按钮。
    upload_btn_loc = (By.CSS_SELECTOR, 'div#fileId a')
    save_btn_loc = (By.CSS_SELECTOR, 'button#addsave')
    back_btn_loc = (By.CSS_SELECTOR, '.box-footer.text-right button.btn-default')

    next_page_loc = (By.CSS_SELECTOR, ".pagination.pull-right li:nth-of-type(4) a")

    page_num_loc = (By.CSS_SELECTOR, ".pagination.pull-right li:nth-of-type(3) a")
    select_all_loc = (By.CSS_SELECTOR, "input#items_selector")

    delete = False

    # 写代码时方便提示, 基本方法完成后删除
    # driver = driver
    def __init__(self, driver=None):
        self.driver = driver
        self.flag = False
        setattr(g, self.class_name, dict())

    @property
    def class_name(self):
        return self.__class__.__name__

    def click_form_btn(self):
        self.driver.find_element(*self.form_btn_loc).click()

    def click_add_btn(self):
        self.driver.find_element(*self.add_btn_loc).click()

    def input_ip_name(self, ele_loc=None, driver=None, keys=''):
        if not ele_loc:
            raise NameError('ele_loc is not defind. --custom')
        value = self.driver.find_element(*ele_loc).get_attribute('value')
        if not value or value == keys:
            BM.input(driver=self.driver, ele_loc=ele_loc, keys=keys)
        # if not value:
        #     self.driver.execute_script(f'document.querySelector("{ele_loc[1]}").value="{keys}"')

    def input_ip_info(self, ipr_num='', ipr_type='', patent_num='', ipr_name='', ipr_getway='', auth_date=''):
        ipr_num = str(ipr_num).zfill(2)
        BM.input(ele_loc=self.ipr_num_loc, driver=self.driver, keys=ipr_num)
        BM.select_value_choice(selector_loc=self.ipr_type_loc, text_value=ipr_type, driver=self.driver)

        BM.input(ele_loc=self.patent_num_loc, driver=self.driver, keys=patent_num)
        self.input_ip_name(ele_loc=self.ipr_name_loc, driver=self.driver, keys=ipr_name)
        BM.select_value_choice(selector_loc=self.ipr_getway_loc, text_value=ipr_getway, driver=self.driver)

        self.driver.execute_script(self.auto_date_js_str)
        BM.input(ele_loc=self.auto_date_loc, driver=self.driver, keys=auth_date)

    @FormDataDecorator
    def main(self, ipr_id='', ipr_type='', auth_num='', ipr_name='', ipr_getway='', auth_date='', oss_path=""):
        # if ipr_id == 2 or ipr_id == "2":
        #     print(1/0)
        # if g.is_first_entry and self.delete:
        #     BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
        #     BM.delete_all(driver=self.driver, page_num_loc=self.page_num_loc, select_all_loc=self.select_all_loc, delete_btn_loc=self.delete_btn_loc)
        #     self.delete = True
        try:
            is_click = False
            class_name = self.class_name
            if getattr(g, class_name) == {}:
                BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
                is_click = True
                BM.cut_over_frame(driver=self.driver, selector_loc=self.content_iframe_loc)
                a_list = getattr(g, class_name)
                table_loc = (By.CSS_SELECTOR, ".tableBody")
                tr_loc = (By.CSS_SELECTOR, ".tableBody tr td:nth-of-type(5)")
                id_loc = (By.CSS_SELECTOR, ".tableBody tr td:nth-of-type(2)")

                while True and g.repetition:
                    BM.wait(driver=self.driver, ele_loc=table_loc)
                    data = self.driver.find_elements(*tr_loc)
                    id_data = self.driver.find_elements(*id_loc)
                    for index, i in enumerate(data):
                        # 获取 标签中的 汉字
                        ipr_name_str = i.text
                        ipr_id_str = id_data[index].text
                        # a_list.append(ipr_name_str)
                        a_list[ipr_id_str] = ipr_name_str
                    if len(data) > 0 or len(id_data) > 0:
                        next_btn = BM.get_ele(driver=self.driver, ele_loc=self.next_page_loc)
                        onclick = next_btn.get_attribute("onclick")
                        if not onclick:
                            # BM.click(driver=self.driver, ele_loc=self.next_page_loc)
                            break
                        else:
                            next_btn.click()
                    else:
                        break
            li_list = getattr(g, class_name)
            if auth_num.startswith('CN'):
                auth_num = auth_num.replace('CN', 'ZL')
            if ipr_type in ["发明专利（非国防专利）","实用新型专利","外观设计专利","发明专利（国防专利）"]:
                if not auth_num.startswith("ZL"):
                    auth_num = "ZL{}".format(auth_num)
            if "IP" + str(ipr_id).zfill(2) in li_list and li_list.get("IP" + str(ipr_id).zfill(2)) == auth_num.replace(" ", ""):
                g.logger.info("{} ----- {}- {} 已存在".format(class_name, auth_num, ipr_name))
                return
            g.logger.info("{}： {}".format(class_name, li_list))
            # if not is_click:
            #     BM.click(driver=self.driver, ele_loc=self.form_btn_loc)

            BM.wait(driver=self.driver, ele_loc=self.add_btn_loc)
            BM.click(driver=self.driver, ele_loc=self.add_btn_loc)
            BM.wait(driver=self.driver, ele_loc=self.save_btn_loc)
            self.input_ip_info(ipr_num=ipr_id, ipr_type=ipr_type, patent_num=auth_num, ipr_name=ipr_name,
                               ipr_getway=ipr_getway, auth_date=auth_date)

            # # TODO 上传附件
            file_path = BM.click_upload_attach(btn_loc=self.upload_btn_loc,
                                               driver=self.driver, class_name=self.class_name, _id=ipr_id)
            BM.input(driver=self.driver, ele_loc=self.ipr_name_loc, keys=ipr_name)
            BM.select_value_choice(selector_loc=self.ipr_getway_loc, text_value=ipr_getway, driver=self.driver)

            self.driver.execute_script(self.auto_date_js_str)
            BM.input(ele_loc=self.auto_date_loc, driver=self.driver, keys=auth_date)
            res = BM.global_click_btn(btn_loc=self.save_btn_loc, driver=self.driver, file_path=file_path)
            if res:
                li_list[ipr_id] = ipr_name
        except Exception as err:
            err_msg = "{} file:{} lines:{}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                           err.__traceback__.tb_lineno)
            raise Exception(err_msg)
